import React from 'react'
import * as AssetAction  from '../actions/AssetAction';
import { connect }  from 'react-redux';
import Paging from './Paging'

import AssetGridCell from './AssetGridCell'

class MenuSettingAssetSelect extends React.Component{
  constructor(props) {
    super(props)

    this.paging = {
      offset: 0,
      limit: 6
    }
  }

  componentDidMount() {
    var self = this;
    var appId = self.props.wechat.length > 0?self.props.wechat[0].appId:''
    this.props.dispatch(
      AssetAction.loadAssetsAsync({
        type: 'news',
        offset: self.paging.offset,
        count: self.paging.limit,
        appId: appId
      })
    )
  }

  componentDidUpdate() {
    // console.log(this.props.assets)
  }

  onPageChange(page) {
    var self = this;
    self.paging.offset = (page-1) * self.paging.limit
    var appId = self.props.wechat.length > 0?self.props.wechat[0].appId:''
    this.props.dispatch(
      AssetAction.loadAssetsAsync({
        type: 'news',
        offset: self.paging.offset,
        count: self.paging.limit,
        appId: appId
      })
    )
  }

  renderAsset() {
    if (this.props.assets.item) {
      var self = this;
      return this.props.assets.item.map(function(item) {
        return (
          <AssetGridCell
            onAssetGridClick={self.props.onAssetGridClick}
            wechat = {self.props.wechat}
            data = {item}/>
        )
      })
    }else {
      return "";
    }
  }

  render() {

    var self = this;

    var offset = parseInt(this.paging.offset),
        limit = parseInt(this.paging.limit)

    var current = Math.ceil(offset/limit) + 1;
    var count = 0;
    if (this.props.assets.item) {
      count = this.props.assets.total_count;
    }

    return(
      <div className="modal fade" id={this.props.ref} tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="Property-modal-label">选择图文</h4>
            </div>
            <div className="modal-body">
              <div className="asset-modal-content row">
                {this.renderAsset()}
              </div>
              <div className="modal-paging">
                <Paging
                  current = {current}
                  count = {count}
                  limit = {limit}
                  onPageChange = {this.onPageChange.bind(self)}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return { assets: state.assets }
}

export default connect(mapStateToProps)(MenuSettingAssetSelect)
